package com.pond.pond.service.impl;

import com.pond.common.core.utils.StringUtils;
import com.pond.common.core.web.domain.AjaxResult;
import com.pond.common.security.utils.SecurityUtils;
import com.pond.pond.domain.FishReturn;
import com.pond.pond.domain.PondOrder;
import com.pond.pond.domain.dto.FishReturnRequest;
import com.pond.pond.domain.dto.OrderQueryRequest;
import com.pond.pond.domain.vo.OrderVO;
import com.pond.pond.mapper.FishReturnMapper;
import com.pond.pond.mapper.PondOrderMapper;
import com.pond.pond.service.IFishReturnService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.HashSet;

/**
 * 回鱼记录Service业务层处理
 */
@Service
public class FishReturnServiceImpl implements IFishReturnService {

    @Autowired
    private FishReturnMapper fishReturnMapper;

    @Autowired
    private PondOrderMapper pondOrderMapper;

    /**
     * 查询回鱼记录列表
     */
    @Override
    public List<FishReturn> selectFishReturnList(FishReturn fishReturn) {
        return fishReturnMapper.selectFishReturnList(fishReturn);
    }

    /**
     * 查询订单列表（用于回鱼操作）
     */
    @Override
    public List<OrderVO> selectOrderListForFishReturn(OrderQueryRequest query) {
        // 查询所有订单（包括已完成的），用于回鱼操作选择
        return pondOrderMapper.selectOrderList(query);
    }

    /**
     * 根据ID查询回鱼记录
     */
    @Override
    public FishReturn selectFishReturnById(Long id) {
        return fishReturnMapper.selectFishReturnById(id);
    }

    /**
     * 根据订单ID查询回鱼记录列表
     */
    @Override
    public List<FishReturn> selectFishReturnByOrderId(Long orderId) {
        return fishReturnMapper.selectFishReturnByOrderId(orderId);
    }

    /**
     * 新增回鱼记录
     */
    @Override
    @Transactional
    public AjaxResult insertFishReturn(FishReturnRequest request) {
        try {
            // 1. 验证订单是否存在且未完成
            PondOrder order = pondOrderMapper.selectOrderById(request.getOrderId());
            if (order == null) {
                return AjaxResult.error("订单不存在");
            }
            if (order.getStatus() == 1) {
                return AjaxResult.error("订单已结束，不能再添加回鱼记录");
            }
            if (order.getStatus() == 2) {
                return AjaxResult.error("订单已取消，不能添加回鱼记录");
            }
            if (order.getStatus() != 0) {
                return AjaxResult.error("只能为未完成的订单添加回鱼记录");
            }

            // 2. 验证回鱼类型和相关字段
            if (!"weight".equals(request.getType()) && !"count".equals(request.getType())) {
                return AjaxResult.error("回鱼类型只能是weight或count");
            }
            
            if ("weight".equals(request.getType())) {
                if (request.getFishWeight() == null || request.getFishWeight().compareTo(BigDecimal.ZERO) <= 0) {
                    return AjaxResult.error("按重量回鱼时，回鱼重量必须大于0");
                }
            } else if ("count".equals(request.getType())) {
                if (request.getFishCount() == null || request.getFishCount() <= 0) {
                    return AjaxResult.error("按条数回鱼时，回鱼条数必须大于0");
                }
            }

            // 3. 创建回鱼记录
            FishReturn fishReturn = new FishReturn();
            BeanUtils.copyProperties(request, fishReturn);
            
            // 设置操作管理员信息
            fishReturn.setAdminId(SecurityUtils.getUserId());
            fishReturn.setAdminName(SecurityUtils.getUsername());
            
            // 根据回鱼类型计算总金额
            BigDecimal totalAmount;
            if ("weight".equals(request.getType())) {
                totalAmount = request.getFishWeight().multiply(request.getUnitPrice());
            } else {
                totalAmount = new BigDecimal(request.getFishCount()).multiply(request.getUnitPrice());
            }
            fishReturn.setTotalAmount(totalAmount);
            
            // 设置创建时间
            fishReturn.setCreateTime(new Date());
            fishReturn.setUpdateTime(new Date());
            
            // 如果是已支付状态，设置支付时间
            if (request.getPayStatus() != null && request.getPayStatus() == 1) {
                fishReturn.setPayTime(new Date());
            }

            // 3. 插入数据库
            int result = fishReturnMapper.insertFishReturn(fishReturn);
            
            if (result > 0) {
                // 4. 回鱼记录添加成功后，将订单状态更新为已结束(1)
                order.setStatus(1);
                order.setUpdateTime(new Date());
                pondOrderMapper.updatePondOrder(order);
                
                return AjaxResult.success("回鱼记录添加成功，订单已自动结束");
            } else {
                return AjaxResult.error("回鱼记录添加失败");
            }
            
        } catch (Exception e) {
            return AjaxResult.error("回鱼记录添加异常：" + e.getMessage());
        }
    }

    /**
     * 修改回鱼记录
     */
    @Override
    @Transactional
    public AjaxResult updateFishReturn(FishReturn fishReturn) {
        try {
            // 验证回鱼类型和相关字段
            if (fishReturn.getType() != null) {
                if (!"weight".equals(fishReturn.getType()) && !"count".equals(fishReturn.getType())) {
                    return AjaxResult.error("回鱼类型只能是weight或count");
                }
                
                if ("weight".equals(fishReturn.getType())) {
                    if (fishReturn.getFishWeight() == null || fishReturn.getFishWeight().compareTo(BigDecimal.ZERO) <= 0) {
                        return AjaxResult.error("按重量回鱼时，回鱼重量必须大于0");
                    }
                } else if ("count".equals(fishReturn.getType())) {
                    if (fishReturn.getFishCount() == null || fishReturn.getFishCount() <= 0) {
                        return AjaxResult.error("按条数回鱼时，回鱼条数必须大于0");
                    }
                }
            }
            
            // 重新计算总金额
            if (fishReturn.getType() != null && fishReturn.getUnitPrice() != null) {
                BigDecimal totalAmount;
                if ("weight".equals(fishReturn.getType()) && fishReturn.getFishWeight() != null) {
                    totalAmount = fishReturn.getFishWeight().multiply(fishReturn.getUnitPrice());
                    fishReturn.setTotalAmount(totalAmount);
                } else if ("count".equals(fishReturn.getType()) && fishReturn.getFishCount() != null) {
                    totalAmount = new BigDecimal(fishReturn.getFishCount()).multiply(fishReturn.getUnitPrice());
                    fishReturn.setTotalAmount(totalAmount);
                }
            }
            
            fishReturn.setUpdateTime(new Date());
            
            int result = fishReturnMapper.updateFishReturn(fishReturn);
            return result > 0 ? AjaxResult.success("修改成功") : AjaxResult.error("修改失败");
            
        } catch (Exception e) {
            return AjaxResult.error("修改异常：" + e.getMessage());
        }
    }

    /**
     * 删除回鱼记录
     */
    @Override
    @Transactional
    public AjaxResult deleteFishReturnById(Long id) {
        try {
            // 1. 先查询回鱼记录，获取关联的订单ID
            FishReturn fishReturn = fishReturnMapper.selectFishReturnById(id);
            if (fishReturn == null) {
                return AjaxResult.error("回鱼记录不存在");
            }
            
            // 2. 删除回鱼记录
            int result = fishReturnMapper.deleteFishReturnById(id);
            
            if (result > 0) {
                // 3. 删除成功后，将对应订单状态重置为未完成(0)
                PondOrder order = pondOrderMapper.selectOrderById(fishReturn.getOrderId());
                if (order != null) {
                    order.setStatus(0); // 重置为未完成状态
                    order.setUpdateTime(new Date());
                    pondOrderMapper.updatePondOrder(order);
                }
                
                return AjaxResult.success("删除成功，订单状态已重置为未完成");
            } else {
                return AjaxResult.error("删除失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("删除异常：" + e.getMessage());
        }
    }

    /**
     * 批量删除回鱼记录
     */
    @Override
    @Transactional
    public AjaxResult deleteFishReturnByIds(String ids) {
        try {
            if (StringUtils.isEmpty(ids)) {
                return AjaxResult.error("删除ID不能为空");
            }
            
            String[] idStrArray = ids.split(",");
            Long[] idArray = new Long[idStrArray.length];
            for (int i = 0; i < idStrArray.length; i++) {
                idArray[i] = Long.parseLong(idStrArray[i].trim());
            }
            
            // 1. 先查询所有要删除的回鱼记录，获取关联的订单ID
            Set<Long> orderIds = new HashSet<>();
            for (Long id : idArray) {
                FishReturn fishReturn = fishReturnMapper.selectFishReturnById(id);
                if (fishReturn != null && fishReturn.getOrderId() != null) {
                    orderIds.add(fishReturn.getOrderId());
                }
            }
            
            // 2. 批量删除回鱼记录
            int result = fishReturnMapper.deleteFishReturnByIds(idArray);
            
            if (result > 0) {
                // 3. 删除成功后，将对应的订单状态重置为未完成(0)
                for (Long orderId : orderIds) {
                    PondOrder order = pondOrderMapper.selectOrderById(orderId);
                    if (order != null) {
                        order.setStatus(0); // 重置为未完成状态
                        order.setUpdateTime(new Date());
                        pondOrderMapper.updatePondOrder(order);
                    }
                }
                
                return AjaxResult.success("批量删除成功，相关订单状态已重置为未完成");
            } else {
                return AjaxResult.error("删除失败");
            }
        } catch (NumberFormatException e) {
            return AjaxResult.error("ID格式错误：" + e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("删除异常：" + e.getMessage());
        }
    }

    /**
     * 更新支付状态
     */
    @Override
    @Transactional
    public AjaxResult updatePayStatus(Long id, Integer payStatus, Integer payType) {
        try {
            Date payTime = (payStatus == 1) ? new Date() : null;
            int result = fishReturnMapper.updatePayStatus(id, payStatus, payType, payTime);
            return result > 0 ? AjaxResult.success("支付状态更新成功") : AjaxResult.error("支付状态更新失败");
        } catch (Exception e) {
            return AjaxResult.error("支付状态更新异常：" + e.getMessage());
        }
    }

    /**
     * 统计订单回鱼总金额
     */
    @Override
    public BigDecimal sumAmountByOrderId(Long orderId) {
        BigDecimal amount = fishReturnMapper.sumAmountByOrderId(orderId);
        return amount != null ? amount : BigDecimal.ZERO;
    }
}